package com.baibei.ebec.follow.fragment;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import com.baibei.ebec.follow.adapter.MyFollowAdapter;
import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.model.UserInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicFragment;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by tang on 2018/8/15.
 */

public class MyFollowFragment extends BasicFragment implements MyFollowAdapter.MyItemClickListener {

    @BindView(R2.id.rv)
    RecyclerView rv;
    Unbinder unbinder;
    private JSONObject jsonObject;
    private String userId;
    private JSONObject job;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_my_follow;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        UserInfo userInfo = SessionManager.getDefault().getUser();
        userId = userInfo.getUserId()+"";
        initView();
    }

    private void initView() {
        AppUI.loading(getContext());
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = BuildConfig.API_BASE_URL+"ddq/api/v1/query/relationship/of/teach";
                OkHttpClient client = new OkHttpClient();
                HashMap<String, String> map = new HashMap<>();
                map.put("userId",userId);
                map.put("type","1");
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    jsonObject = new JSONObject(response.body().string());
                    LogUtils.e("myfollows", jsonObject.toString());
                    if (!"SUCCESS".equals(jsonObject.optString("code"))){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast(jsonObject.optString("message"));
                            }
                        });
                        AppUI.dismiss();
                        return;
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showData();
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showData() {
        LinearLayoutManager llm = new LinearLayoutManager(getContext());
        rv.setLayoutManager(llm);
        MyFollowAdapter myFollowAdapter = new MyFollowAdapter(jsonObject.optJSONArray("data"), "取消跟买",getContext());
        myFollowAdapter.setOnItemClick(this);
        rv.setAdapter(myFollowAdapter);
        AppUI.dismiss();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View view, MyFollowAdapter.ViewName viewName, final int position) {
        if (viewName == MyFollowAdapter.ViewName.IMAGE){
            AppRouter.routeToFollowerDetail(getContext(),jsonObject.optJSONArray("data").optJSONObject(position).optString("followerId"));
            return;
        }
        AppUI.dismiss();
        AppUI.loading(getContext());
        new Thread(new Runnable() {

            @Override
            public void run() {
                String url = BuildConfig.API_BASE_URL + "ddq/api/v1/get/notget/teacher";
                OkHttpClient client = new OkHttpClient();
                HashMap<String, String> map = new HashMap<>();
                map.put("userId", userId);
                map.put("followerId", jsonObject.optJSONArray("data").optJSONObject(position).optString("followerId"));
                map.put("type", "1");
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    job = new JSONObject(response.body().string());
                    if (!"SUCCESS".equals(job.optString("code"))){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast(job.optString("message"));
                            }
                        });
                        AppUI.dismiss();
                        return;
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            AppUI.dismiss();
                            popDialog();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void popDialog() {
        final Dialog dialog = new Dialog(getContext());
        Window window = dialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.dialog_follow);
        TextView tvContent = dialog.findViewById(R.id.tv_content);
        TextView tvCancel = dialog.findViewById(R.id.tv_cancel);
        TextView tvEnsure = dialog.findViewById(R.id.tv_ensure);
        tvContent.setText(job.optJSONObject("data").optString("message"));
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                initView();
            }
        });
        tvEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                initView();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
}
